package com.sms.controller;

import com.sms.dto.PhoneCodeDto;
import com.sms.utils.SMSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

import static com.commons.utils.Constance.PHONE_KEY;


/**
 * @author mis_wu
 * @date 2021/12/11 11:42
 * 使用阿里巴巴短信验证接口
 * 发送验证码  手机获取验证码接口
 */
@RestController
@RequestMapping("/phone-services")
@Api(tags = "PhoneCode-Service-Api 电话验证码微服务接口")
public class SendPhoneCodeCtrl {

    public static final Logger log = LoggerFactory.getLogger(SendPhoneCodeCtrl.class);

    //注入StringRedisTemplate<String,String>
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SMSUtils smsUtils;

    @PostMapping("/captchas")
    @ApiOperation("获取手机验证码")
    public void sendPhoneCode(@ApiParam("验证码") @RequestBody PhoneCodeDto phoneCodeDto){
        //0、获取接收的手机号
        String phone=phoneCodeDto.getPhone();
        log.info("发送短息的手机号为 {}",phone);
        //1、每次发送验证码前判断是否超时
        String timeOutKey=PHONE_KEY+phone; //TIMEOUT_phone
        if (stringRedisTemplate.hasKey(timeOutKey)){
            throw new RuntimeException("tips:不允许重复发送!");
        }
        try {
            //2、生成验证码 4位随机数
            String code= RandomStringUtils.randomNumeric(4);
            log.info("发送的验证码 {}",code);
            //3、根据手机号发送验证码
            smsUtils.sendMsg(phone,code);
            //4、将手机号对应验证码存入redis
            String phoneKey=PHONE_KEY+phone;
            stringRedisTemplate.opsForValue().set(phoneKey,code,5, TimeUnit.MINUTES);//2分钟内有效
            //5、如果验证码在有效期内,不允许重复发送
            stringRedisTemplate.opsForValue().set(timeOutKey,"true",2,TimeUnit.MINUTES);//两次发送间隔时间
        }catch (Exception e){
            throw new RuntimeException("tips:短信发送失败!");
        }
    }
}
